package router

import (
	"encoding/json"
	logger "gitee.com/zaper/private-logger"
	"gitee.com/zaper/route-service/constant"
	"gitee.com/zaper/route-service/model"
	"gitee.com/zaper/route-service/nginx_handler"
	"gitee.com/zaper/route-service/os_env"
	"gitee.com/zaper/service-center-client/global_sign"
	srvcerutil "gitee.com/zaper/service-center-client/util"
	reg "gitee.com/zaper/software-framework/register"
	"gitee.com/zaper/software-framework/router"
	fmkutil "gitee.com/zaper/software-framework/util"
	"github.com/gin-gonic/gin"
	"io"
	"path/filepath"
)

func InitializeRegister() {
	go func() {
		port := srvcerutil.GetListenPort()
		model.NginxPortChan <- port
		global_sign.PortChan <- port
		httpRouter := router.GetHttpRouter()
		httpRouter.RegisterRouteInstance(groups, routes, port)
		reg.InitializeRouter()
	}()
}

var groups = []string{"/api/v1/", "/api/v2"}

var routes = []router.Router{
	{groups[0], "/nginx/dynconf", constant.HttpPOST, []router.Option{dynamicConf}},
}

func dynamicConf(context *gin.Context) {
	resp, _ := io.ReadAll(context.Request.Body)
	svrConf := &model.ServerConf{}
	err := json.Unmarshal(resp, svrConf)
	if err != nil {
		logger.Errorf("request body Unmarshal fail, err is %s", err)
		errBody := fmkutil.NewHttpResponseError(10001, "request body fail")
		fmkutil.HttpContextJSON(context, errBody)
	}
	workSpace := filepath.Join(os_env.NginxWorkspaceValue, nginx_handler.NginxConf)
	_ = nginx_handler.NginxConfHandler(workSpace, svrConf)
	nginx_handler.DynamicReLoadNginx()
	errBody := fmkutil.NewHttpResponseError(0, "dynamicConf success!")
	fmkutil.HttpContextJSON(context, errBody)
}
